//
//  HMusercount.swift
//  WeiBo
//
//  Created by 李立达 on 15/12/8.
//  Copyright © 2015年 heima11. All rights reserved.
//

import UIKit

let WEB_APPKEY = "3344270075"
let WEB_APPSECRET = "e0b61cae79f3d5aed4827acba7eac316"
let WEB_REDIRECT_URI = "http://itheima.com"

class HMusercount {

    static let shareuserCount : HMusercount  = {
    
        let hmuser = HMusercount()
    
        return hmuser
    }()
    
    var userAccount :HMuserCount?
    
    var accessToken : String? {
    
    
        if let accessToken = userAccount?.access_token where !isExpires{
        
            return accessToken
        }
        return nil
    }
    
    
    var isLogin : Bool {
        return accessToken != nil
    }
    
    var isExpires : Bool {
    
        guard let expries = userAccount?.expriesDate else
        {
            return true
        }
        
        if NSDate().compare(expries) == NSComparisonResult.OrderedAscending
        {
                return false
        }
        return true
    }
    
    var archivePath: String = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("useraccount.archive")
    private init(){
       
        userAccount = loadUserAccount()
    }
  

    
    func  loadAccessToken(code : String, compelet : (isSucess : Bool)->() ){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = [
            
            "client_id":"3344270075",
            
            "client_secret":"e0b61cae79f3d5aed4827acba7eac316",
            
            "grant_type" : "authorization_code",
            
            "code":code,
            
            "redirect_uri":"http://itheima.com",
        ]
        
        HMhttpSession.sharanetWork.request(.POST, url: urlString, parmers: params) { (response,  error) -> () in
            
            if error != nil
            {
                print("请求失败:\(error)")
                
                compelet(isSucess: false)
                return
                
            }
            else
            {
            guard let dict = response as?[String : AnyObject] else
            {
                return
            }
            
            let account = HMuserCount(dict: dict)
            self.userAccount = account            
                self.loadUserinFor(account.uid!, access_token: account.access_token!, compelet: compelet)
            }
            }

        }
    
    /**
    
        loadUserINfo
    */
    
    private func loadUserinFor(uid: String ,access_token:String ,compelet : (isSucess : Bool)->()){
    
        let userinfoUrl = "https://api.weibo.com/2/users/show.json"
        
        let pamres = [
            "access_token" : access_token,
            "uid" : uid
        ]
        
        HMhttpSession.sharanetWork.request(.GET, url: userinfoUrl, parmers: pamres) { (response, error) -> () in
            
            if((error) != nil)
            {
                print("请求失败\(error)")
                compelet(isSucess: false)
                    return
            }
            guard let dict = response as?[String : AnyObject] else
            {
                print("不是一个字典")
                return
            }
            print(dict)
            self.userAccount?.screen_name = dict["screen_name"] as? String
            self.userAccount?.avatar_large = dict["avatar_large"] as? String
            self.savaAccout(self.userAccount!)
            compelet(isSucess: true)
        }
    
    }
    
}
//归档的读取与保存
extension HMusercount
{
    func savaAccout(accout : HMuserCount){
    
    NSKeyedArchiver.archiveRootObject(accout, toFile: archivePath)
    
    }
    func loadUserAccount() -> HMuserCount? {
    
    
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(archivePath) as? HMuserCount
        
        return result
    }

}